//
//  PushTopicViewController.m
//  Findif
//
//  Created by Mac on 2019/2/25.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "PushTopicViewController.h"
#import "TopicTableViewCell.h"
#import "PushTopicTableViewCell.h"
#import "TopicHeaderView.h"
#import "TopicModel.h"

@interface PushTopicViewController ()<UITableViewDelegate,UITableViewDataSource,PushTopicTableViewCellDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UIButton * rightButton;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, strong)PushTopicTableViewCell *cell;
@property (nonatomic, copy)NSString * img;
@property (nonatomic, strong)NSArray <TopicModel *>* historyArray;

@end

@implementation PushTopicViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [[ZRNetworkTool sharedTool] getTopicListWithPromulgator_id:self.group_id WithBlock:^(BOOL success, id responseData) {
        
        //        NSLog(@"res==%@",responseData);
        if (success) {
            
            NSDictionary * dict = responseData[@"data"];
            
            self.historyArray = [NSArray yy_modelArrayWithClass:[TopicModel class] json:dict[@"history"]];
            
        }
    }];
}

- (void)setHistoryArray:(NSArray<TopicModel *> *)historyArray{
    
    _historyArray = historyArray;
    
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNav{
    
    self.title = @"话题";
    
    UIButton * rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 15 * SCREENH6)];
    
    [rightButton setTitle:@"发布" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didSetUpButton) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.rightButton = rightButton;
    
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
}

- (void)setupUI{
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
    tableView.rowHeight = 80 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    //    TableViewHeader * headerView =  [[TableViewHeader alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 270 * SCREENH6)];
    //    // 设置header
    //    tableView.tableHeaderView = headerView;
    //    self.tableView.bounces = NO;
    //    self.tableView.estimatedRowHeight = 150 * SCREENH6;//估算高度
    //    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[TopicTableViewCell class] forCellReuseIdentifier:@"PushTopicTableViewCell"];
    [self.tableView registerClass:[PushTopicTableViewCell class] forCellReuseIdentifier:@"PushTopicCell"];
    [self.tableView registerClass:[TopicHeaderView class] forHeaderFooterViewReuseIdentifier:@"PushTopicHeaderView"];
    
    //    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //
    //        [self loadData];
    //    }];
    
    [self.view addSubview:self.tableView];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 1;
    }else{
        
        return self.historyArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
       
        self.cell = [tableView dequeueReusableCellWithIdentifier:@"PushTopicCell" forIndexPath:indexPath];
        
        self.cell.delegate = self;
        //    cell.model = self.goodlistArray[indexPath.row];
        
        return self.cell;
    }else{
        
        TopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PushTopicTableViewCell" forIndexPath:indexPath];
        
        cell.model = self.historyArray[indexPath.row];
        
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30 * SCREENH6;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    TopicHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"PushTopicHeaderView"];
    
    if (section == 0) {
        
        header.titleLabel.text = @"今日话题";
    }else{
        
        header.titleLabel.text = @"历史活动";
    }
    
    return header;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    
    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF4F5F6);
    }
}


- (void)didSetUpButton{

    if (!self.img) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先添加话题封面"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }else if (self.cell.titleTextField.text.length <= 0){
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先添加话题"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        ShowHUD;
        
        NSDictionary * dict = @{@"promulgator_id":self.group_id,@"topic_title":self.cell.titleTextField.text,@"topic_img":self.img};
        
        [[ZRNetworkTool sharedTool] addTopicWithDict:dict WithBlock:^(BOOL success, id responseData) {
            
            HiddenHUD;
            if (success) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                        
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
}


- (void)clickImageViewButton{
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        
        self.alertVC.popoverPresentationController.sourceView = self.view;
        self.alertVC.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
        //            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    [self presentViewController:self.alertVC animated:YES completion:nil];
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    NSString *base64Data = [frontImageData base64EncodedStringWithOptions:0];
    NSString * reslut = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",base64Data];
    
    
    [[ZRNetworkTool sharedTool] uploadOneImgResultWithImg:reslut WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            [self.cell.iconButton setImage:image forState:UIControlStateNormal];
            self.img = [NSString stringWithFormat:@"%@",responseData[@"data"]];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


@end
